# ~*~ coding: utf-8 ~*~
import sys
import json
import os
import importlib
import configparser
import requests
import socket
importlib.reload(sys)

#加载django
#import django
#CMDB_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#sys.path.append(CMDB_PATH)
#os.environ.setdefault("DJANGO_SETTINGS_MODULE","syscmdb.settings")
#django.setup()


from paramiko_api import *
from mailers import SendMessages
from DingDing import SendMs
from configs import *
from mysqldb import DbSearch
from Log import logger,logger_task
#from mysqldb import DbSearch

from celery import Celery,platforms
platforms.C_FORCE_ROOT = True
app = Celery('butterfly',backend=CELERY_RESULT_BACKEND,broker=BROKER_URL,include=['tasks'],)
app.conf.CELERY_IGNORE_RESULT = False
#json报错,注释了
#app.conf.CELERY_ACCEPT_CONTENT = [CELERY_ACCEPT_CONTENT]
app.conf.CELERY_TASK_SERIALIZER = CELERY_TASK_SERIALIZER
app.conf.CELERY_RESULT_SERIALIZER = CELERY_RESULT_SERIALIZER
app.conf.CELERY_TIMEZONE = CELERY_TIMEZONE


#日志
@app.task
def RemoteDispatch(ip_list,item_list,MSG):

	alert_type = MSG['alert_type']
	alert_type_link = MSG['alert_type_link']
	user = MSG['user']
	alarm = MSG['alarm']
	db = DbSearch()

	ACCESS_LIST = []
	ERROR_LIST = []

	#自愈处于维护状态,为了防止第一次自愈没有启动完成,第二次自愈开始导致异常报错。
	db.DevStatus(alarm,0)

	logger_task.info('开始执行')

	ip_num = len(ip_list)
	for n in range(0,ip_num):


		asset = db.Asset(int(ip_list[n]))
		action = db.AutoAction(int(item_list[n]))

		logger.info(asset)
		logger.info(action)
		#try:
		if 1 == 1:
			sm = SSHConnection(asset)
			result = sm.run_cmd(action)
			ds = 0
		#except Exception as e:
		#	result = e
		#	ds = 1

		logger_task.info(result)
		hostname = asset['hostname']
		if ds == 0:
			stdout = '主机%s,监控项%s,自愈动作%s,执行成功!执行日志:%s'%(hostname,alarm,action,str(result['stdout']))
			errout = ''
		else:
			stdout = ''
			errout = '主机%s,监控项%s,自愈动作%s,执行失败!执行日志:%s' % (hostname,alarm,action,str(result))

		ACCESS_LIST.append(stdout)
		ERROR_LIST.append(errout)

	try:
		if alert_type == 1:
			SendMessages(alert_type_link, ACCESS_LIST, ERROR_LIST, user)
		if alert_type == 2:
			mes = ','.join(ACCESS_LIST) + ','.join(ERROR_LIST)
			atl = alert_type_link.split('|')[0]
			keyword = '关键词:' + alert_type_link.split('|')[1] + ', '
			mes = keyword + mes
			SendMs(atl, mes)
	except Exception as e:
		logger_task.info('check 错误')
		logger_task.info(e)
	# 自愈状态设置正常
	db.DevStatus(alarm, 1)


